package com.xyy.saas.payment.util.xydSign;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Base64;

/**
 * @author XYD
 * @description:
 * @createDate: 2021/12/17
 * @updateDate: 2021/12/17
 * @updateBy: XYD
 */
public class SignDemo {


    // 20250318
    /**
     * 提供给小雨点 对请求报文解签
     */
    private final static String B2B_TEST_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPrDY7BlAsLt7RONmU7E3zJD2JWQrKb+5pV6MXI2zGA+k/Tjuoje1x5k/jxydVucAvH0cQDtU+5WW8dW5yhcevBg1++EWlZL9WXHvESfhZOKFlxI+E+acgCRzYnHdBMDTCbhSUyuRYmIaSthUooa1UYniOaSKXs2nbt82i/MGMzQIDAQAB";

    /**
     * 药帮忙请求加密
     */
    private final static String B2B_TEST_PRIVATE_KEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAI+sNjsGUCwu3tE42ZTsTfMkPYlZCspv7mlXoxcjbMYD6T9OO6iN7XHmT+PHJ1W5wC8fRxAO1T7lZbx1bnKFx68GDX74RaVkv1Zce8RJ+Fk4oWXEj4T5pyAJHNicd0EwNMJuFJTK5FiYhpK2FSihrVRieI5pIpezadu3zaL8wYzNAgMBAAECgYAD6lOIBEIHEjfsR7pWPqJZL/GlXpHWtnou0L6XENYUB2NB4GXr0AJaikY/FNxTj75XCmkrXNwe3K2LF0AtSswIRDmyKZfekl1wWJyJLnz71UZV07leTpdvvw8BIvhhEY8oWGPnSLO+XfaFkdlP+qGevmzaRJS4icpKEpWM4ZfnQQJBAPh/mYvpW6CpyewH1jwhMZN6yEjei8PodFl07vkyy0Gihtm8v7WPC0ZewwiDGxeZUHoh7B4bfXqz4AppmjzjskkCQQCUAoRXtyPkMK5CdWSXIjepbUQIRuZLkZ1IDxZc0KOFnbagomoRLCeFoSQxmdFYioBRUalBI5wC+/OGdQZKyoZlAkBeVpLEOuM+KzctFAyQ50ka5BIFF/eXeDgzfeD7Wf0v/bOUFcPx+Uweevsv0BYI73tN4nLxOx535rG3Qj/7vbWBAkEAh4FGaIfi9CcdYvrW/Qb2rsa6YlmGveiydiZZ8t+Q1eNuL+KB+PbTuCOvXznTz5v9nnWE334adyDz80VwXUjNgQJALgmszP2gpP9/ju9rEjBDJLcbWS6Z/sfMcW6LmbVdgNsLNdrNb+RC6QTazyJQj6wHjHMDRC3lpoILqVgpd0e2Pw==";

    public static final String B2B_PROD_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDnkoqNFjA0xTI7xzuoTD8z6+o5YzzKofAPuGn4mMXJ7QbqVBymlSbWujytR75HVUnEzuIwDQLnSuME45RWpFNY8d7jtErBYgWA6joUFVM7HuVW1BQPkLuYety+21MAvysmKsp7b28cuTj5naxoK/CZUsQRV0V/aYtW50nc493giwIDAQAB";
    public static final String B2B_PROD_PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAOeSio0WMDTFMjvHO6hMPzPr6jljPMqh8A+4afiYxcntBupUHKaVJta6PK1HvkdVScTO4jANAudK4wTjlFakU1jx3uO0SsFiBYDqOhQVUzse5VbUFA+Qu5h63L7bUwC/KyYqyntvbxy5OPmdrGgr8JlSxBFXRX9pi1bnSdzj3eCLAgMBAAECgYEAgN5tGjzJ0OQYo2mpSmw8E/Hqo8sVDpL13Fm9J2olT80HNypd01pXhdGYaLnvKxVMeyjCeQkUn5BuK89WQq0p79twV0GZOxo7d/kSKFm4YSrAZszTOIqQnrt+Teg1+VptC/TlZggdhSCO1188a9qOIq+0on0Rbp3AEGhWP48lqSECQQD7W3rP+xF78ti2qXFErpKRmGlnnEiOfAhgCg4OE6dm9QJ60/acAOxhTVatPoRozV/68P5aoNW0D470VmWll+6xAkEA69mCo5N7Otc1mAuE/bASkfbeA8oOBGxSn0T7kUTBxHzu4bolhYbRWd1xqc9NdWuVgdxWl3QycXDfOqmRTZSp+wJAYVxAyNieIB2jlbUyO4FHIoAfq9NcQ1yFvfWHFirEt9uFV2BM8IZnCRV00mwZy6JpYAEC9MXBoRo5rCje/HJKMQJAHakjJtM7YjECinaYaRclnrm/PhbBIIlG8sTIJoLRI5barASvB1XnKjgRPVvWz/eRu90r/qwcU+vwBv6gSXNy1QJBAI9jLweq1YKoQ6GoD8lnmKnLhbms1Aa7vWs9xn9A6U9rKNgZFVJOFG3j6m5TBYpbi8ejEtzcj/7YVuBVk1crd30=";

    /**
     * 公钥私钥生成
     *
     * @throws NoSuchAlgorithmException
     */
    public static void getKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(EncryptUtils.KEY_RSA);
        keyPairGenerator.initialize(1024, new SecureRandom());
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();
        PublicKey aPublic = (RSAPublicKey) keyPair.getPublic();
        System.out.println("=====");
        System.out.println("public:--->" + (new String(Base64.getEncoder().encodeToString(aPublic.getEncoded()))));
        System.out.println("private:--->" + (new String(Base64.getEncoder().encodeToString(aPrivate.getEncoded()))));
        System.out.println("=====");
    }

    public static void main(String[] args) {
        /*try {
            getKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }*/
        String bizParam = "{" +
                "  \"auth\": {" +
                "    \"businessLicense\": \"111111111111111111111\"," +
                "    \"mobile\": \"17322222222\"," +
                "    \"thirdUserNo\": \"testThirdUserNo001\"" +
                "  }" +
                "}";
        bizParam = "{" +
                "    \"h5Url\": \"https://titan-frontend.dev.xiaoyudian.com/borrowMoney?token=20211217155805669249099892572160iid6gaqmhg01\"" +
                "  }";
        bizParam = "{" +
                "        \"code\":\"0\"," +
                "        \"data\":" +
                "        \"accessKey\":\"E1327040490\"," +
                "        \"success\":true," +
                "        \"sign\":\"w/hlnsqGUDbIdKZEaBBzBUN9OIDifooIfaAsk2/Kf5KPFEfGe7Uk8uOh2/Sw6YW5lpfp8UcZwZDyzzjg9ov+XSRX0wnNy3mla0R3u77rpQlU71pW/J4fhsx/ZjGPHi9FiWkP0zU41+ojXe65myS700T06Yv9USlFXvk/73zN7PY=\"," +
                "        \"platType\":\"H5\"," +
                "        \"timestamp\":\"1639982465769\"" +
                "}";

        bizParam = "{\n" +
                "\t\"thirdOrderNo\": \"11\",\n" +
                "\t\"platformCode\": \"06\",\n" +
                "\t\"productNo\": \"B2B-KZCF-CGD\",\n" +
                "\t\"orderInfo\": {\n" +
                "\t\t\"businessName\": \"借款企业名称9\",\n" +
                "\t\t\"orgName\": \"服务站名称（客户名称）\",\n" +
                "\t\t\"orgCode\": \"服务站编码（客户编码）\",\n" +
                "\t\t\"orderTotalCount\": \"订单笔数（借款人向平台采购）\",\n" +
                "\t\t\"orderTotalAmt\": \"订单金额（借款人向平台采购）\",\n" +
                "\t\t\"refundOrderList\": [\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"refundTotalCount\": \"11\",\n" +
                "\t\t\t\t\"refundTotalAmt\": \"22\",\n" +
                "\t\t\t\t\"refundReason\": \"111\"\n" +
                "\t\t\t},\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"refundTotalCount\": \"11\",\n" +
                "\t\t\t\t\"refundTotalAmt\": \"22\",\n" +
                "\t\t\t\t\"refundReason\": \"111\"\n" +
                "\t\t\t}\n" +
                "\t\t],\n" +
                "\t\t\"saleRefundOrderList\": [\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"refundTotalCount\": \"11\",\n" +
                "\t\t\t\t\"refundTotalAmt\": \"22\",\n" +
                "\t\t\t\t\"refundReason\": \"111\"\n" +
                "\t\t\t},\n" +
                "\t\t\t{\n" +
                "\t\t\t\t\"refundTotalCount\": \"11\",\n" +
                "\t\t\t\t\"refundTotalAmt\": \"22\",\n" +
                "\t\t\t\t\"refundReason\": \"111\"\n" +
                "\t\t\t}\n" +
                "\t\t],\n" +
                "\t\t\"saleTotalCount\": \"1\",\n" +
                "\t\t\"saleTotalAmt\": \"1\"\n" +
                "\t},\n" +
                "\t\"logisticsInfo\": {\n" +
                "\t\t\"orderId\": \"11\",\n" +
                "\t\t\"receiveAddress\": \"收货地址\",\n" +
                "\t\t\"receiveName\": \"收货人\"\n" +
                "\t}\n" +
                "}";
//        bizParam = "{\"auth\":{\"businessLicense\":\"1\",\"mobile\":\"\",\"thirdUserNo\":\"test01\"},\"platformCode\":\"07\",\"productNo\":\"B2B-BB-CGD\"}";
//        bizParam = "{\"auth\":{\"businessLicense\":\"1\",\"mobile\":\"\",\"thirdUserNo\":\"test01\"},\"productNo\":\"B2B-BB-CGD\",\"platformCode\":\"07\"}";
        bizParam = "{\"auth\":{\"businessLicense\":\"00000000AA0000AA0A\",\"creditType\":\"ORDER\",\"mobile\":\"13333333333\",\"thirdUserNo\":\"1122333\"},\"platformCode\":\"09\",\"productNo\":\"GYL-YCD-CGD\"}";
        bizParam = "{\"productNo\": \"GYL-YCD-CGD\", \"platformCode\": 10, \"auth\": {\"businessLicense\": \"123456\", \"mobile\": \"18888888888\", \"thirdUserNo\": \"txl001\"}}";

        // 请求时实时获取
        String timestamp = String.valueOf(System.currentTimeMillis());
        String sign = testSign(bizParam, timestamp);


        JSONObject response = new JSONObject();
        response.put("appkey", "E0000000015");
        response.put("timestamp", timestamp);
//        response.put("sign", "JpeWZcL0N6Om0qFjsfLZAGaGaj0ZErufYIa3eGhrd5OF3bgYNT9mvyeorhgksrZIVGTbs4ra+5PZnC44U3oADC/ltuw1BCG7peYL8CMtYdZwTPFVBja/7TED2++y1q0Ha+qiI6sAhNtcOfDp1FmgOnLZ3gPaYbZr9SvEhN2Jyxo=");
        response.put("sign", sign);
        response.put("body", bizParam);
        boolean b = testVerify(JSON.toJSONString(response));
        System.out.println(b);
    }

    /**
     * 加签
     */
    public static String testSign(String bizParam, String timestamp) {
//        JSONObject body = JSONObject.parseObject(bizParam);
        String signData = EncryptUtils.getMd5SignData(timestamp, bizParam);
        String sign = null;
        try {
            //
            // b2b 自己保存获取 通过appkey找到对应的秘钥（b2b生成公钥私钥，并提供给小雨点公钥）
            String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMi2mmNZgm/k/r3tpqcckHhX+206JnJtZbrMJQpDXQ/L1lLfDUJ3KUYV0Ii+6n2xc6/Cdn8hG4jNJjni2FfGp4J4MBaaXA2gdBMw54diRLUtuKQSDBuPbRYqre/JfkWRnb+FEyMCY3CbfbsXEb3jHlHHOYNKDivV2f3zRrHbR6cnAgMBAAECgYEAnoBlR1OmSArEiOQlmQ5boE2KheVH+1Ec5vjTv1kXIqRL6kGuzPAhLfGILpTlxMDfpMqinR5eChhHuarEQfzkxiNMsBl2V6KJrciHMCqZ0LRN9VFTefGFkIXdtnyl5ZqHJv9vn4LQI/09XOKUs1weK0hfFTiihZgIa1rUGcyMZ7ECQQDpXzqvHJsJducJoLlHaQotzcHMAIusAQDPgvDEX9baexz1CP6xf96suNpwBy6MiUdc+KKF1y8Qg7lOuIUOPPjTAkEA3Cy31q2eulHxkPpeYoNJqYx6LviKoVl+jPzaivqCieu2L/dPlenv6LAmtG2wB8b5MFGHpGkD0mA2rXtENuAj3QJAQhrbgKbVs8SehTelw/iZDYhvEN5Gsh5GoIEyui17qr+c4DwACT9zT/G8zmb6ZIyuTkOPpeHiTwdBAm96ISJcSQJBAIQXN/vNkcrKWpjV/EYx6cGUi8EeT11ZqbjAAgUbIbHI/jZsswyHmu0IsU/R9qfT0bARWcVjU22lV2hg6Z3afukCQEfZ8joPOgKFLo5cmh8+/GzlKd8Fcc1JA/1HOpb1Hc/oo/zeS1DSmMVIb3U/Mkwg3CaLuXQZbQrsj6ESaDz6D28=";
            privateKey = B2B_PROD_PRIVATE_KEY;

            sign = EncryptUtils.sign(signData.getBytes(), privateKey, EncryptUtils.KEY_SHA_RSA);
            System.out.println("" + sign);
            System.out.println(timestamp);

            return sign;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

    public static boolean testVerify(String response) {
        JSONObject jsonResp = JSON.parseObject(response);

        String accessKey = jsonResp.getString("accessKey");
        String timestamp = jsonResp.getString("timestamp");
        String sign = jsonResp.getString("sign");
        String body = jsonResp.getString("body");
        try {
            // 验签
            // 通过appkey找到小雨点提供的公钥(可以不用appkey关联，只要能识别公钥即可)
            // // b2b 自己保存获取（小雨点生成公钥私钥，并提供给b2b公钥）
            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDItppjWYJv5P697aanHJB4V/ttOiZybWW6zCUKQ10Py9ZS3w1CdylGFdCIvup9sXOvwnZ/IRuIzSY54thXxqeCeDAWmlwNoHQTMOeHYkS1LbikEgwbj20WKq3vyX5FkZ2/hRMjAmNwm327FxG94x5RxzmDSg4r1dn980ax20enJwIDAQAB";
            publicKey = B2B_PROD_PUBLIC_KEY;

            boolean verify = EncryptUtils.verify(publicKey, timestamp, body, sign);
            return verify;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
